package com.mryan.ps_common.interceptor;

import com.mryan.ps_common.entity.PSResponse;
import com.mryan.ps_common.entity.constant.PSConstant;
import com.mryan.ps_common.utils.PSUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @BelongsProject: ps_cloud
 * @BelongsPackage: com.mryan.ps_common.interceptor
 * @Author: Yan
 * @CreateTime: 2021-04-25 21:53
 * @Description: 系统全局拦截器--微服务防护核心
 */
public class PSServerProtectInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//		在请求头中获取Zuul Token
		String token = request.getHeader(PSConstant.ZUUL_TOKEN_HEADER);
		String zuulToken = new String(Base64Utils.encode(PSConstant.ZUUL_TOKEN_VALUE.getBytes()));
//		校验zuul Token的正确性
		if (StringUtils.equals(token, zuulToken)) {
			return true;
		} else {
			PSResponse psResponse = new PSResponse();
			PSUtils.makeResponse(response, MediaType.APPLICATION_JSON_UTF8_VALUE, HttpServletResponse.SC_FORBIDDEN,
					psResponse.message("请通过网关获取资源"));
			return false;
		}
	}
}
